package com.platform.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.dao.UserDao;
import com.platform.dao.UserMsgDao;
import com.platform.entity.UserEntity;
import com.platform.entity.UserMsgEntity;
import com.platform.toutiao.bean.TouTiaoCode2SessionResult;
import com.platform.toutiao.bean.TouTiaoUserInfo;
import com.platform.utils.Constant;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * Service接口
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-16 15:02:28
 */
@Service("userService")
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMsgDao userMsgDao;

    public UserEntity queryObjectByUnionId(String unionId) {
        return userDao.queryObjectByUnionId(unionId);
    }
    public UserEntity queryObjectByOpenId(String openId) {
        return userDao.queryObjectByOpenId(openId);
    }

    public UserEntity queryObject(Integer id) {
        return userDao.queryObject(id);
    }

    public List<UserEntity> queryList(Map<String, Object> map) {
        return userDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return userDao.queryTotal(map);
    }
    
    public UserEntity loginByPassword(String code,String password) throws Exception{
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(code, 0);
    	if(userMsg != null) {
    		UserEntity user  = userDao.queryObject(userMsg.getUserId());
    		if(password.equalsIgnoreCase(new Sha256Hash(user.getPassword()).toHex())) {
    			return user;
    		}else {
        		throw new Exception("会员帐号或密码错误！");
    		}
    	}else {
    		throw new Exception("会员帐号或密码错误！");
    	}
    }

    @Transactional
    public UserEntity loginByWx(WxMpUser wxUser,Integer mpId,String ip,Integer referenceId) {
    	UserEntity user = null;
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(wxUser.getOpenId(), mpId);
    	if(userMsg != null) {
    		user = userDao.queryObject(userMsg.getUserId());
    		if(StringUtils.isNotBlank(wxUser.getUnionId()) && StringUtils.isBlank(userMsg.getUnionId())) {
        		userMsgDao.updateUnionId(wxUser.getUnionId(), userMsg.getId());
    			UserEntity unionUser = userDao.queryObjectByUnionId(wxUser.getUnionId());
    			if(unionUser != null && !unionUser.getId().equals(userMsg.getUserId())) {	//之前通过小程序等其他已绑定
    				//TODO 余额，已经购权限是否转移
    				userMsgDao.updateUserId(userMsg.getUserId(), userMsg.getId());
    			}
    		}
    	}else {
    		if(StringUtils.isNotBlank(wxUser.getUnionId())) {
    		user = userDao.queryObjectByUnionId(wxUser.getUnionId());
	    	}else {
	    		user = userDao.queryObjectByOpenId(wxUser.getOpenId());
	    	}
    	}
		Date nowDate = new Date();
		if(user == null) {
		    user = new UserEntity();
		    user.setUsername(wxUser.getNickname());
		    user.setGender(wxUser.getSex());
		    user.setRegisterTime(nowDate);
		    user.setRegisterIp(ip);
		    user.setNickname(wxUser.getNickname());
		    user.setAvatar(wxUser.getHeadImgUrl());
		    user.setWeixinOpenid(wxUser.getOpenId());
		    user.setWeixinUnionid(wxUser.getUnionId());
		    user.setUserLevelId(0);
		    user.setLevelName("访客");
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    user.setParentId(referenceId);
		    userDao.save(user);
		}else {
			//是否要更新
            if(user.getParentId().equals(0) && !user.getParentId().equals(user.getId())) {
			    user.setParentId(referenceId);
            }
            if(StringUtils.isNotBlank(wxUser.getUnionId()) && StringUtils.isBlank(user.getWeixinUnionid())) {
    		    user.setWeixinUnionid(wxUser.getUnionId());
            }
            user.setNickname(wxUser.getNickname());
            user.setAvatar(wxUser.getHeadImgUrl());
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    userDao.update(user);
		}
	    if(userMsg == null) {
		    saveWxUserMsg(wxUser.getOpenId(),wxUser.getUnionId(),mpId,user.getId());
	    }
        return user;
    }

    @Transactional
	public UserEntity loginByWxXcx(WxMaUserInfo wxUser, Integer mpId, String ip, Integer referenceId) {
    	UserEntity user = null;
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(wxUser.getOpenId(), mpId);
    	
    	if(userMsg != null) {
    		user = userDao.queryObject(userMsg.getUserId());
    		if(StringUtils.isNotBlank(wxUser.getUnionId()) && StringUtils.isBlank(userMsg.getUnionId())) {
        		userMsgDao.updateUnionId(wxUser.getUnionId(), userMsg.getId());
    			UserEntity unionUser = userDao.queryObjectByUnionId(wxUser.getUnionId());
    			if(unionUser != null && !unionUser.getId().equals(userMsg.getUserId())) {	//之前通过小程序等其他已绑定
    				//TODO 余额，已经购权限是否转移
    				userMsgDao.updateUserId(userMsg.getUserId(), userMsg.getId());
    			}
    		}
    	}else if(StringUtils.isNotBlank(wxUser.getUnionId())) {
    		user = userDao.queryObjectByUnionId(wxUser.getUnionId());
    	}else {
    		user = userDao.queryObjectByOpenId(wxUser.getOpenId());
    	}
    	
		Date nowDate = new Date();
		if(user == null) {
		    user = new UserEntity();
		    user.setUsername(wxUser.getNickName());
		    user.setGender(0);
		    user.setRegisterTime(nowDate);
		    user.setRegisterIp(ip);
		    user.setNickname(wxUser.getNickName());
		    user.setAvatar(wxUser.getAvatarUrl());
		    user.setWeixinOpenid(wxUser.getOpenId());
		    user.setWeixinUnionid(wxUser.getUnionId());
		    user.setUserLevelId(0);
		    user.setLevelName("访客");
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    user.setParentId(referenceId);
		    userDao.save(user);
		}else {
			//是否要更新
            if(user.getParentId().equals(0) && !user.getParentId().equals(user.getId())) {
			    user.setParentId(referenceId);
            }
            if(StringUtils.isNotBlank(wxUser.getUnionId()) && StringUtils.isBlank(user.getWeixinUnionid())) {
    		    user.setWeixinUnionid(wxUser.getUnionId());
            }
            user.setNickname(wxUser.getNickName());
            user.setAvatar(wxUser.getAvatarUrl());
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    userDao.update(user);
		}
	    if(userMsg == null) {
		    saveWxUserMsg(wxUser.getOpenId(),wxUser.getUnionId(),mpId,user.getId());
	    }
        return user;
    }
    
    @Transactional
    public UserEntity loginByWxXcx(WxMaJscode2SessionResult wxOpenIdUnionId,Integer mpId,String ip,Integer referenceId) {
    	UserEntity user = null;
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(wxOpenIdUnionId.getOpenid(), mpId);
    	
    	if(userMsg != null) {
    		user = userDao.queryObject(userMsg.getUserId());
    		if(StringUtils.isNotBlank(wxOpenIdUnionId.getUnionid()) && StringUtils.isBlank(userMsg.getUnionId())) {
        		userMsgDao.updateUnionId(wxOpenIdUnionId.getUnionid(), userMsg.getId());
    			UserEntity unionUser = userDao.queryObjectByUnionId(wxOpenIdUnionId.getUnionid());
    			if(unionUser != null && !unionUser.getId().equals(userMsg.getUserId())) {	//之前通过小程序等其他已绑定
    				//TODO 余额，已经购权限是否转移
    				userMsgDao.updateUserId(userMsg.getUserId(), userMsg.getId());
    			}
    		}
    	}else if(StringUtils.isNotBlank(wxOpenIdUnionId.getUnionid())) {
    		user = userDao.queryObjectByUnionId(wxOpenIdUnionId.getUnionid());
    	}else {
    		user = userDao.queryObjectByOpenId(wxOpenIdUnionId.getOpenid());
    	}
    	
		Date nowDate = new Date();
		if(user == null) {
		    user = new UserEntity();
		    user.setUsername("访客");
		    user.setGender(0);
		    user.setRegisterTime(nowDate);
		    user.setRegisterIp(ip);
		    user.setNickname("访客");
		    user.setWeixinOpenid(wxOpenIdUnionId.getOpenid());
		    user.setWeixinUnionid(wxOpenIdUnionId.getUnionid());
		    user.setUserLevelId(0);
		    user.setLevelName("访客");
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    user.setParentId(referenceId);
		    userDao.save(user);
		}else {
			//是否要更新
            if(user.getParentId().equals(0) && !user.getParentId().equals(user.getId())) {
			    user.setParentId(referenceId);
            }
            if(StringUtils.isNotBlank(wxOpenIdUnionId.getUnionid()) && StringUtils.isBlank(user.getWeixinUnionid())) {
    		    user.setWeixinUnionid(wxOpenIdUnionId.getUnionid());
            }
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    userDao.update(user);
		}
	    if(userMsg == null) {
		    saveWxUserMsg(wxOpenIdUnionId.getOpenid(),wxOpenIdUnionId.getUnionid(),mpId,user.getId());
	    }
        return user;
    }
    
    
    @Transactional
    public UserEntity loginByTtXcx(TouTiaoCode2SessionResult ttSessionResult,Integer mpId,String ip,Integer referenceId) {
    	UserEntity user = null;
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(ttSessionResult.getOpenId(), mpId);
    	
    	if(userMsg != null) {
    		user = userDao.queryObject(userMsg.getUserId());
    	}else {
    		user = userDao.queryObjectByOpenId(ttSessionResult.getOpenId());
    	}
    	
    	Date nowDate = new Date();
    	if(user == null) {
    		user = new UserEntity();
    		user.setUsername("访客");
    		user.setGender(0);
    		user.setRegisterTime(nowDate);
    		user.setRegisterIp(ip);
    		user.setNickname("访客");
    		user.setWeixinOpenid(ttSessionResult.getOpenId());
    		user.setUserLevelId(0);
    		user.setLevelName("访客");
    		user.setLastLoginTime(nowDate);
    		user.setLastLoginIp(ip);
    		user.setParentId(referenceId);
    		userDao.save(user);
    	}else {
    		//是否要更新
    		if(user.getParentId().equals(0) && !user.getParentId().equals(user.getId())) {
    			user.setParentId(referenceId);
    		}
    		user.setLastLoginTime(nowDate);
    		user.setLastLoginIp(ip);
    		userDao.update(user);
    	}
    	if(userMsg == null) {
    		saveWxUserMsg(ttSessionResult.getOpenId(),null,mpId,user.getId());
    	}
    	return user;
    }
    
    @Transactional
	public UserEntity loginByTtXcx(TouTiaoUserInfo ttUser, Integer mpId, String ip, Integer referenceId) {
    	UserEntity user = null;
    	UserMsgEntity userMsg = userMsgDao.queryByOpenId(ttUser.getOpenId(), mpId);
    	
    	if(userMsg != null) {
    		user = userDao.queryObject(userMsg.getUserId());
    	}else {
    		user = userDao.queryObjectByOpenId(ttUser.getOpenId());
    	}
    	
		Date nowDate = new Date();
		if(user == null) {
		    user = new UserEntity();
		    user.setUsername(ttUser.getNickName());
		    user.setGender(0);
		    user.setRegisterTime(nowDate);
		    user.setRegisterIp(ip);
		    user.setNickname(ttUser.getNickName());
		    user.setAvatar(ttUser.getAvatarUrl());
		    user.setWeixinOpenid(ttUser.getOpenId());
		    user.setUserLevelId(0);
		    user.setLevelName("访客");
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    user.setParentId(referenceId);
		    userDao.save(user);
		}else {
			//是否要更新
            if(user.getParentId().equals(0) && !user.getParentId().equals(user.getId())) {
			    user.setParentId(referenceId);
            }
            user.setNickname(ttUser.getNickName());
            user.setAvatar(ttUser.getAvatarUrl());
		    user.setLastLoginTime(nowDate);
		    user.setLastLoginIp(ip);
		    userDao.update(user);
		}
	    if(userMsg == null) {
		    saveWxUserMsg(ttUser.getOpenId(),null,mpId,user.getId());
	    }
        return user;
    }
    
    
    
    
    
    
    
    
        
	private void saveWxUserMsg(String openId,String unionId,Integer mpId,Integer userId) {
    	UserMsgEntity userMsg = new UserMsgEntity();
    	userMsg.setAppId(mpId);
    	userMsg.setOpenId(openId);
    	userMsg.setUnionId(unionId);
    	userMsg.setUserId(userId);
    	userMsgDao.save(userMsg);
    }
    
    public int save(UserEntity user) {
    	user.setPassword(new Sha256Hash(user.getPassword()).toHex());
        int result = userDao.save(user);
        
    	UserMsgEntity userMsg = new UserMsgEntity();
    	userMsg.setOpenId(user.getWeixinOpenid());
    	userMsg.setAppId(0);
    	userMsg.setUserId(user.getId());
    	userMsgDao.save(userMsg);
    	return result;
    }

    public int update(UserEntity user) {
        return userDao.update(user);
    }
    public Map<String,Object> statisticsChildrenMsg(Map<String, Object> params){
    	return userDao.statisticsChildrenMsg(params);
    }
    public int delete(Integer id) {
        return userDao.delete(id);
    }

    public int deleteBatch(Integer[] ids) {
        return userDao.deleteBatch(ids);
    }
}
